package com.advertisementsystem.Controller;

import com.advertisementsystem.Dto.NegotiationQueryDTO;
import com.advertisementsystem.Exception.BusinessException;
import com.advertisementsystem.Servie.NegotiationService;
import com.advertisementsystem.Exception.ResponseResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.advertisementsystem.Dto.NegotiationDTO;
import com.advertisementsystem.vo.NegotiationVO;
/**
 * 广告协商控制器
 * 处理广告主与设备所有者之间的协商相关请求
 */
@RestController
@RequestMapping("/negotiation")
@Slf4j
public class NegotiationController {

    @Autowired
    private NegotiationService negotiationService;

    /**
     * 创建协商
     */
    @PostMapping
    @PreAuthorize("hasRole('DEVICE_OWNER')")
    public ResponseResult<?> createNegotiation(@RequestBody @Valid NegotiationDTO dto) {
        negotiationService.createNegotiation(dto);
        return ResponseResult.success();
    }

    /**
     * 获取协商列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<IPage<NegotiationVO>> getNegotiationList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String adname,
            @RequestParam(required = false) Long deviceId,
            @RequestParam(required = false) String status) {
        log.info("Get negotiation list, pageNum: {}, pageSize: {}, adId: {}, deviceId: {}",
                pageNum, pageSize, adname, deviceId);
        return ResponseResult.success(
                negotiationService.getNegotiationList(pageNum, pageSize, adname, deviceId,status));
    }

    /**
     * 完成协商
     */
    @PutMapping("/{id}/complete")
    @PreAuthorize("hasAnyRole('ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<?> completeNegotiation(@PathVariable Long id) {
        negotiationService.completeNegotiation(id);
        return ResponseResult.success();
    }

    /**
     * 取消协商
     */
    @PutMapping("/{id}/cancel")
    @PreAuthorize("hasAnyRole('ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<?> cancelNegotiation(@PathVariable Long id) {
        negotiationService.cancelNegotiation(id);
        return ResponseResult.success();
    }

    /**
     * 更新协商内容
     * 双方可以更新协商的价格、时段和内容
     *
     * @param id  协商ID
     * @param dto 更新的协商信息，包含：
     *            - 价格
     *            - 播放时段
     *            - 协商内容
     * @return 更新结果
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<?> updateNegotiation(
            @PathVariable Long id,
            @RequestBody @Valid NegotiationDTO dto) {
        try {
            negotiationService.updateNegotiation(id, dto);
            return ResponseResult.success();
        } catch (BusinessException e) {
            log.error("Update negotiation failed: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("Update negotiation error", e);
            return ResponseResult.error("系统错误，请稍后重试");
        }
    }
    /**
     * 获取协商详情
     * 查看单个协商的详细信息
     *
     * @param id 协商ID
     * @return 协商详情，包含：
     *         - 广告信息
     *         - 协商双方信息
     *         - 价格和时段
     *         - 协商状态和内容
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<NegotiationVO> getNegotiationDetail(@PathVariable Long id) {
        try {
            NegotiationVO vo = negotiationService.getNegotiationDetail(id);
            log.info("Get negotiation detail: {}", vo);
            return ResponseResult.success(vo);
        } catch (BusinessException e) {
            log.error("Get negotiation detail failed: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("Get negotiation detail error", e);
            return ResponseResult.error("系统错误，请稍后重试");
        }
    }

}